import React, { useState } from 'react';
import {
  Grid,
  Card,
  CardMedia,
  CardContent,
  Typography,
  Box,
  Chip,
  IconButton,
  Menu,
  MenuItem,
  TextField,
  InputAdornment,
  Select,
  FormControl,
  InputLabel,
  SelectChangeEvent,
  Stack,
  ToggleButtonGroup,
  ToggleButton,
} from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import FilterListIcon from '@mui/icons-material/FilterList';
import GridViewIcon from '@mui/icons-material/GridView';
import ViewListIcon from '@mui/icons-material/ViewList';
import AccessTimeIcon from '@mui/icons-material/AccessTime';

interface Game {
  id: number;
  title: string;
  coverImage: string;
  playTime: string;
  lastPlayed: string;
  tags: string[];
}

// Mock data
const mockGames: Game[] = [
  {
    id: 1,
    title: "赛博朋克 2077",
    coverImage: "https://via.placeholder.com/300x400",
    playTime: "42小时",
    lastPlayed: "2023-12-25",
    tags: ["RPG", "开放世界", "科幻"],
  },
  // ... 更多游戏数据
];

interface GameLibraryProps {
  games?: Game[];
}

const GameLibrary: React.FC<GameLibraryProps> = ({ games = mockGames }) => {
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState('lastPlayed');
  const [filterAnchorEl, setFilterAnchorEl] = useState<null | HTMLElement>(null);

  const handleViewModeChange = (
    event: React.MouseEvent<HTMLElement>,
    newMode: 'grid' | 'list',
  ) => {
    if (newMode !== null) {
      setViewMode(newMode);
    }
  };

  const handleSortChange = (event: SelectChangeEvent) => {
    setSortBy(event.target.value);
  };

  const handleFilterClick = (event: React.MouseEvent<HTMLElement>) => {
    setFilterAnchorEl(event.currentTarget);
  };

  const handleFilterClose = () => {
    setFilterAnchorEl(null);
  };

  const filteredGames = games.filter(game =>
    game.title.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const sortedGames = [...filteredGames].sort((a, b) => {
    switch (sortBy) {
      case 'lastPlayed':
        return new Date(b.lastPlayed).getTime() - new Date(a.lastPlayed).getTime();
      case 'title':
        return a.title.localeCompare(b.title);
      case 'playTime':
        return parseInt(b.playTime) - parseInt(a.playTime);
      default:
        return 0;
    }
  });

  return (
    <Box>
      <Stack
        direction={{ xs: 'column', sm: 'row' }}
        spacing={2}
        alignItems="center"
        sx={{ mb: 3 }}
      >
        <TextField
          size="small"
          placeholder="搜索游戏..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
          }}
          sx={{ flexGrow: 1 }}
        />

        <FormControl size="small" sx={{ minWidth: 120 }}>
          <InputLabel>排序方式</InputLabel>
          <Select
            value={sortBy}
            label="排序方式"
            onChange={handleSortChange}
          >
            <MenuItem value="lastPlayed">最近游玩</MenuItem>
            <MenuItem value="title">名称</MenuItem>
            <MenuItem value="playTime">游戏时长</MenuItem>
          </Select>
        </FormControl>

        <IconButton onClick={handleFilterClick}>
          <FilterListIcon />
        </IconButton>

        <ToggleButtonGroup
          value={viewMode}
          exclusive
          onChange={handleViewModeChange}
          size="small"
        >
          <ToggleButton value="grid">
            <GridViewIcon />
          </ToggleButton>
          <ToggleButton value="list">
            <ViewListIcon />
          </ToggleButton>
        </ToggleButtonGroup>
      </Stack>

      <Menu
        anchorEl={filterAnchorEl}
        open={Boolean(filterAnchorEl)}
        onClose={handleFilterClose}
      >
        <MenuItem>全部游戏</MenuItem>
        <MenuItem>已安装</MenuItem>
        <MenuItem>收藏的</MenuItem>
        <MenuItem>最近游玩</MenuItem>
      </Menu>

      <Grid container spacing={2}>
        {sortedGames.map((game) => (
          <Grid
            item
            key={game.id}
            xs={12}
            sm={viewMode === 'grid' ? 6 : 12}
            md={viewMode === 'grid' ? 4 : 12}
            lg={viewMode === 'grid' ? 3 : 12}
          >
            <Card
              sx={{
                display: viewMode === 'list' ? 'flex' : 'block',
                height: '100%',
              }}
            >
              <CardMedia
                component="img"
                image={game.coverImage}
                alt={game.title}
                sx={{
                  width: viewMode === 'list' ? 140 : '100%',
                  height: viewMode === 'list' ? 140 : 200,
                }}
              />
              <Box sx={{ flex: 1 }}>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    {game.title}
                  </Typography>
                  <Box sx={{ mb: 1 }}>
                    {game.tags.map((tag) => (
                      <Chip
                        key={tag}
                        label={tag}
                        size="small"
                        sx={{ mr: 0.5, mb: 0.5 }}
                      />
                    ))}
                  </Box>
                  <Stack
                    direction="row"
                    spacing={2}
                    alignItems="center"
                    sx={{ color: 'text.secondary' }}
                  >
                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                      <AccessTimeIcon sx={{ fontSize: 16, mr: 0.5 }} />
                      <Typography variant="body2">
                        {game.playTime}
                      </Typography>
                    </Box>
                    <Typography variant="body2">
                      最后游玩：{game.lastPlayed}
                    </Typography>
                  </Stack>
                </CardContent>
              </Box>
            </Card>
          </Grid>
        ))}
      </Grid>
    </Box>
  );
};

export default GameLibrary;
